# -*- coding: utf-8 -*- 

import sys
from Cheetah.Template import Template

from database import mysql

class Meta:
  def __init__(self, project):
    self.db = mysql.MySQL('model')
    self.project = project
    sql = "select name from tables where project = '%s'"   %(self.project)
    print sql
    self._result_set = self.db.fetchall(sql)  
    self.tables = {}
  def gettabs(self):
    return self._result_set
    
  def getcols(self, table):
    sql = "select column_type, name, tablename, attribute, data_type, width, scale, not_null, default_value, ispk, isfk, ordering from columns where project='%s' and tablename = '%s'" %(self.project,table)
    #sql = sql.upper()
    #print sql
    return self.db.fetchall(sql)
    
  def gettabinfo(self):
    
    for tab in self.gettabs():
      colsinfo = {}
      cols = self.getcols(tab['name'])
      for col in cols:
        #print col['tablename'],col['name']
        colsinfo[col['ordering']] = col
      self.tables[tab['name']] = colsinfo
      #print 

  def mapping(self, data_type, width=None):
    data_type = data_type.lower()
    
    if data_type == 'integer':      
      map_type = 'Integer'
    elif data_type == 'varchar':
      map_type = 'String(%s)'%(width)
    elif data_type == 'datetime':
      map_type = 'DateTime'
    elif data_type == 'date':
      map_type = 'Date'
    elif data_type == 'tinyint':
      map_type = 'SmallInteger'      
    elif data_type == 'smallint':
      map_type = 'SmallInteger'
    elif data_type == 'text':
      map_type = 'String(2000)'
    else:
      print data_type, width
      print "please provide new type in mapgen mapping"
      sys.exit(0)
      
    return map_type

  def gettabsinfo(self):
    return self.tables

def test():
  gen = Meta('model')
  gen.gettabinfo()
  tabs = gen.gettabsinfo()
  
  project_meta = {}
  tab_meta ={}
  for tab in tabs:
    #print "====" + tab + "===="
    cols_meta = {}
    j = 0
    for x in range(1,len(tabs[tab])+1):
      item = tabs[tab][x]
      if item['name'].lower() == 'language':
        continue
      j = j +1

      col_meta = {}
      #if item['name'].lower()[0:3] == 'pk_':
      #  print 'pk: ',item['name'].lower()
      col_meta['name'] = item['name'].lower()
      col_meta['is_pk'] = item['ispk']
      col_meta['is_fk'] = item['isfk']   
      #print item['default_value']
     
      if item['default_value'] == '0000-00-00 00:00:00' or item['default_value'] == '0000-00-00':
        col_meta['default_value'] = ',default = datetime.now()'
      elif item['default_value'] == '' or item['default_value'] == None:
        col_meta['default_value'] = ''
      else:
        col_meta['default_value'] = ", default = %s" %(item['default_value'])
      
      col_meta['data_type'] =  gen.mapping(item['data_type'],item['width'])  #"%s(%s)" %(item['data_type'],item['width'])
      col_meta['column_type'] = item['column_type']
      #col_meta['default'] = item['column_type']
      if item['not_null'] == 1:
        col_meta['nullable'] = 'False'
      else:
        col_meta['nullable'] = 'True'
      if item['isfk'] ==1:
        col_meta['nullable'] = 'True'
        #print item['name'].lower()
      cols_meta[j] = col_meta
      
    project_meta[tab] = cols_meta
    #project_meta['name'] =  tab
    #project_meta['len'] = len(cols_meta)
    
  return project_meta
  



def output(dict):
    pathout = "table_meta.py"
    output = open(pathout, 'w') 
    #nameSpace = {'tabdict':tabdict}     
    pathin = "table_tpl.py"
    sp = Template(file=pathin)
    sp.tables = dict
    sp = "%s"%(sp)
    #print sp.encode('utf8')
    output.writelines(sp)

def main():
  meta = test()
  #print meta
  output(meta)


if __name__ == "__main__":
  main()

